import {
    Table,
    Modal,
    Form,
    Radio,
    Select,
    Input,
    Badge,
    message,
} from 'antd';
import React, {PureComponent} from 'react';
const FormItem = Form.Item;
const {Option} = Select;
import {status, statusMap} from './orderStatus';

@Form.create()
export default class SendGoods extends PureComponent {
    state = {
        loading: false,
        type: 'Flow',
        data: [],
        selectedRowKeys: [],
        company: [],
        initalExpressId: 5,
        initalExpressNo: '',
    };

    componentWillMount() {
        const {dispatch} = this.props;
        dispatch({
            type: 'orderList/getExpressCompany',
            payload: {
                callback: (res)=> {
                    console.log(res);
                    this.setState({
                        company: res
                    });
                }
            }
        })
    }

    componentWillReceiveProps(props) {
        if (props.id != this.props.id) {
            this.setState({
                loading: true,
            });
            props.dispatch({
                type: 'orderList/getOrderDetail',
                payload: {
                    id: props.id
                }
            }).then(()=> {
                this.setState({
                    loading: false
                });
            });
        } else if (props.data && props.data != this.state.data) {
            let selectedRowKeys = [];
            if(props.data.goods_list){
                selectedRowKeys = props.data.goods_list.map(v=>{
                    if(v.status < 103){
                        return v.id;
                    }
                });
            }
            this.setState({
                data: props.data,
                selectedRowKeys,
            });
        }
        if (!props.show) { //关闭显示，清空选中
            this.setState({
                selectedRowKeys: []
            });
        }
    };

    handleOk = ()=> {
        const {selectedRowKeys} = this.state;
        const {form, dispatch, sendDispatchType, id} = this.props;
        form.validateFields((err, fieldsValue) => {
            console.log(err, fieldsValue);
            if (err) {
                return false;
            }
            if (selectedRowKeys.length == 0) {
                message.error('你还未选择需要发货的商品');
                return false;
            }
            let postData = {
                ...fieldsValue,
                ids: selectedRowKeys.join(','),
                orderId: id, //列表里面需要使用订单ID更改状态
            };
            dispatch({
                type: sendDispatchType,  //orderDetail/sendGoods || orderList/sendGoods
                payload: postData
            }).then(()=> {
                form.resetFields();
                this.handleCancel();
            });
        });
    };

    handleCancel = ()=> {
        this.props.form.resetFields();
        this.props.hideSendGoods();
    };

    handleChange = (e)=> {
        console.log(e.target.value);
        if (e.target.value == 2) {
            this.setState({
                type: ''
            });
        } else {
            this.setState({
                type: 'Flow'
            });
        }
    };

    onSelectChange = (selectedRowKeys) => {
        console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({selectedRowKeys});
    }


    render() {
        const {selectedRowKeys, loading, type, data, company, initalExpressId, initalExpressNo} = this.state;
        const {show} = this.props;
        const {getFieldDecorator} = this.props.form;
        console.log('selectedRowKeys', selectedRowKeys);
      console.log('company', company, this.props.form.getFieldValue('expressId'));
        const rowSelection = {
            selectedRowKeys: selectedRowKeys,
            onChange: this.onSelectChange,
            getCheckboxProps: record => ({
                disabled: record.status > 103, //不能被选中的项，103包含已发货，可以去修改物流
                status: record.status,
            }),
        };

        const formItemLayout = {
            labelCol: {
                xs: {span: 24},
                sm: {span: 3},
            },
            wrapperCol: {
                xs: {span: 24},
                sm: {span: 12},
            },
        };

        const columns = [
            {
                title: '商品图片',
                dataIndex: 'img',
                key: 'img',
                render: (val)=><img src={val} width={50}/>
            },
            {
                title: '商品名称',
                dataIndex: 'name',
                key: 'name',
            },
            {
                title: '规格',
                render: (v, record)=> {
                    let key = '';
                    let value = '';
                    for (let k in record.sku) {
                        key = k;
                        value = record.sku[key];
                    }
                    return value + ' ' + key;
                }
            },
            {
                title: '单价',
                dataIndex: 'unit_price',
                key: 'unit_price',
            },
            {
                title: '数量',
                dataIndex: 'count',
                key: 'count',
            },
            {
                title: '金额',
                dataIndex: 'price',
                key: 'price',
            },
            {
                title: '状态',
                dataIndex: 'status',
                key: 'status',
                render: val => {
                    // let result = null;
                    // switch(val){
                    //   case 102 :
                    //     result = <Badge status="warning" text="等待发货" />;
                    //     break;
                    //   case 103 :
                    //     result = <Badge status="success" text="已发货" />;
                    //     break;
                    //   case 104 :
                    //     result = <Badge status="default" text="交易完成" />;
                    //     break;
                    //   case 105 :
                    //     result = <Badge status="error" text="交易关闭" />;
                    //     break;
                    //   default :
                    //     break;
                    // }
                    // return result;
                    console.log('status', status);
                    return <Badge status={statusMap[val]} text={status[val]}/>;
                }
            },
            {
                title: '物流|单号',
                render: (a, record)=> {
                    return record.expressName ? <div>{record.expressName} | {record.expressNo}</div> : null
                }
            },
        ];

        const companyList = company.map(v=> {
          return <Option key={`expressId${v.id}`} value={v.id}>{ v.name }</Option>
        });

        return <Modal
            title="商品发货"
            width={900}
            visible={ show }
            onOk={this.handleOk}
            onCancel={this.handleCancel}
        >

            <Form onSubmit={this.handleSubmit} style={{marginTop: '24px'}}>
                <FormItem
                    {...formItemLayout}
                    label="收货信息"
                >
                    {data.addressee} {data.phone} {data.province}{data.city}{data.area}{data.address}
                </FormItem>
                <FormItem
                    {...formItemLayout}
                    label="发货方式"
                >
                    {
                        getFieldDecorator('public', {
                            initialValue: '1',
                        })(
                            <Radio.Group onChange={this.handleChange}>
                                <Radio value="1">物流发货</Radio>
                                <Radio value="2">无需物流</Radio>
                            </Radio.Group>
                        )
                    }
                </FormItem>
                {
                    type == 'Flow' ? <div>
                        <FormItem
                            {...formItemLayout}
                            label="物流公司"
                        >
                            {getFieldDecorator('expressId', {
                                initialValue: 5,
                                rules: [
                                    {
                                        required: true,
                                        message: '请选择物流公司',
                                    },
                                ],
                            })(
                                <Select placeholder="请选择物流公司" style={{width: '100%'}}>
                                    {
                                        companyList
                                    }
                                </Select>
                            )}
                        </FormItem>
                        <FormItem
                            {...formItemLayout}
                            label="物流单号"
                        >
                            {getFieldDecorator('expressNo', {
                                initialValue: initalExpressNo,
                                rules: [
                            {
                                required: true,
                                message: '物流单号不能为空',
                            },
                                ],
                            })(
                                <Input placeholder="请输入物流单号" />
                                )}
                        </FormItem>
                    </div> : null
                }
            </Form>
            <Table
                bordered={true}
                pagination={false}
                loading={loading}
                dataSource={data.goods_list}
                columns={columns}
                rowSelection={rowSelection}
                rowKey="id"
            />
        </Modal>
    }
}

